/**
 * 文件上传插件
 */
import {apiObj} from "@/utils/api-obj.js";
var uploadFileList = []; //上传视频存放的路径
var uploadFileListQiniu = []; //上传七牛之后文件存放的路径
var HmacSha1 = require('crypto-js/hmac-sha1') ;
var Base64New = require('crypto-js/enc-base64');
var Base64 = {
	
	    // private property
	    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	
	    // public method for encoding
	    encode: function(input) {
	        var output = "";
	        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	        var i = 0;
	
	        input = Base64._utf8_encode(input);
	
	        while (i < input.length) {
	
	            chr1 = input.charCodeAt(i++);
	            chr2 = input.charCodeAt(i++);
	            chr3 = input.charCodeAt(i++);
	
	            enc1 = chr1 >> 2;
	            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	            enc4 = chr3 & 63;
	
	            if (isNaN(chr2)) {
	                enc3 = enc4 = 64;
	            } else if (isNaN(chr3)) {
	                enc4 = 64;
	            }
	
	            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
	
	        }
	
	        return output;
	    },
	
	    // public method for decoding
	    decode: function(input) {
	        var output = "";
	        var chr1, chr2, chr3;
	        var enc1, enc2, enc3, enc4;
	        var i = 0;
	
	        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	
	        while (i < input.length) {
	
	            enc1 = this._keyStr.indexOf(input.charAt(i++));
	            enc2 = this._keyStr.indexOf(input.charAt(i++));
	            enc3 = this._keyStr.indexOf(input.charAt(i++));
	            enc4 = this._keyStr.indexOf(input.charAt(i++));
	
	            chr1 = (enc1 << 2) | (enc2 >> 4);
	            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	            chr3 = ((enc3 & 3) << 6) | enc4;
	
	            output = output + String.fromCharCode(chr1);
	
	            if (enc3 != 64) {
	                output = output + String.fromCharCode(chr2);
	            }
	            if (enc4 != 64) {
	                output = output + String.fromCharCode(chr3);
	            }
	
	        }
	
	        output = Base64._utf8_decode(output);
	
	        return output;
	
	    },
	
	    // private method for UTF-8 encoding
	    _utf8_encode: function(string) {
	        string = string.replace(/\r\n/g, "\n");
	        var utftext = "";
	
	        for (var n = 0; n < string.length; n++) {
	
	            var c = string.charCodeAt(n);
	
	            if (c < 128) {
	                utftext += String.fromCharCode(c);
	            } else if ((c > 127) && (c < 2048)) {
	                utftext += String.fromCharCode((c >> 6) | 192);
	                utftext += String.fromCharCode((c & 63) | 128);
	            } else {
	                utftext += String.fromCharCode((c >> 12) | 224);
	                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }
	
	        }
	
	        return utftext;
	    },
	
	    // private method for UTF-8 decoding
	    _utf8_decode: function(utftext) {
	        var string = "";
	        var i = 0;
	        var c = c1 = c2 = 0;
	
	        while (i < utftext.length) {
	
	            c = utftext.charCodeAt(i);
	
	            if (c < 128) {
	                string += String.fromCharCode(c);
	                i++;
	            } else if ((c > 191) && (c < 224)) {
	                c2 = utftext.charCodeAt(i + 1);
	                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	                i += 2;
	            } else {
	                c2 = utftext.charCodeAt(i + 1);
	                c3 = utftext.charCodeAt(i + 2);
	                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	                i += 3;
	            }
	
	        }
	
	        return string;
	    }
	
	}
export default {
	//去除文件左边的/符号
	leftTrim(str) {  
	  if (str.charAt(0) == '/') {  
	    str = str.slice(1);  
	    str = this.leftTrim(str);  
	  }  
	  return str;  
	}, 
	getSuffix(fileName){
		var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
		return fileExtension;
	},
	base64ToUrlSafe (v){
	  return v.replace(/\//g, '_').replace(/\+/g, '-');
	},
	getQiniuToken(){
	  var accessKey = '2YdeZhRXvRjLXEpkUug_kPCUZM-0wNUVjMzR3xyO';
	  var secretkey = 'dUzBvruu-4ysglLiW03C7X1e04QUwnbPvHxPD0IV';
	  var bucket = 'renlian-photo-test';
	  var strdata = {
		"scope": bucket,
	    "deadline":parseInt(Date.parse(new Date()) / 1000) + 600, //当前时间截
	  }	
	  var str = JSON.stringify(strdata);
	  
	  var encoded = Base64.encode(str);
	  var encodedStr = this.base64ToUrlSafe(encoded);
	  //console.log(encodedStr)
	  var sign = Base64New.stringify((HmacSha1(encodedStr,secretkey)));
	  var encodedSign = this.base64ToUrlSafe(sign); 
	  //var sign = CryptoJS.HmacSHA1(encodedStr, secretkey).toString(CryptoJS.enc.hex);
	  var token = accessKey + ':' + encodedSign + ':' + encodedStr;
	  //console.log(Base64.encode(sign))
	  return {
		  token:token,
		  token_exp_time:strdata.deadline
	  };
	},
	// 初始化七牛相关参数
	async getQiniuConfig(fileName,suffix){
		var cacheKey = 'qiniuUploadConfig'; ////七牛缓存key
		var cacheInfo = uni.getStorageSync(cacheKey);
		var nowTime = parseInt((Date.parse(new Date())) / 1000);
		var qiniuConfigInfo = {
			token:'',
			uploadurl:'https://upload-z2.qiniup.com',
			cdnurl:'http://r8q1x0neu.hn-bkt.clouddn.com',
			savekey:'{year}{mon}{day}{hour}{min}{second}{.suffix}',
			fileName:'',
		}
		
		if(cacheInfo.token && cacheInfo.token_exp_time &&  (cacheInfo.token_exp_time - nowTime > 60))
		{
			qiniuConfigInfo = cacheInfo;
		}else{
			var tokenInfo = this.getQiniuToken();
			qiniuConfigInfo.token = tokenInfo.token;
			qiniuConfigInfo.token_exp_time = tokenInfo.token_exp_time;
			uni.setStorageSync(cacheKey,qiniuConfigInfo);
			
		}
		let  savefileName = qiniuConfigInfo.savekey;
		if(fileName && savefileName)
		{
			let nowDate = new Date();
			let year = nowDate.getFullYear();
			let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1): nowDate.getMonth() + 1;
			let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
			let hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
			let min = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
			let second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
			//var ip = uni.getStorageSync('getIpName');
			//savefileName = savefileName.replace('{ip}',(ip?ip:'ip_is_null'));
			savefileName = savefileName.replace('{year}',year);
			savefileName = savefileName.replace('{mon}',month);
			savefileName = savefileName.replace('{day}',day);
			savefileName = savefileName.replace('{hour}',hour);
			savefileName = savefileName.replace('{min}',min);
			savefileName = savefileName.replace('{second}',second);
			savefileName = savefileName.replace('{.suffix}','.'+suffix);
			qiniuConfigInfo.fileName = this.leftTrim(savefileName);
		}else{
			qiniuConfigInfo.fileName = '';
		}
		return qiniuConfigInfo;
	},
	async initQiniu(file,suffix) {
		suffix = suffix?suffix:'jpg';
		//console.log(file)
		var qiniuConfigInfo = await this.getQiniuConfig(file,suffix);
		if(!qiniuConfigInfo.fileName)
		{
			return {};
		}
		var options = {
			uploadURL: qiniuConfigInfo.uploadurl, // 华北区
			//uptokenURL: 'https://yourserver.com/api/uptoken',
			uptoken: qiniuConfigInfo.token,
			domain: qiniuConfigInfo.cdnurl,
			key:qiniuConfigInfo.fileName,
		};
		return options;
	},
	encode(str){
		// 对字符串进行编码
		var encode = encodeURI(str);
		// 对编码的字符串转化base64
		var base64 = btoa(encode);
		return base64;
	},
	
	/**
	 * 上传文件至七牛
	 */
	async uploadFileToQiniu(res,fileObj){
		
		var that = this;
		uploadFileList = [];
		return new Promise(async (resolve, reject) =>  {
			uploadFileListQiniu = [];
			for(var i = 0;i<res.length;i++)
			{
				res[i].tempFilePath = res[i].path;
			}
			 await that.uploadFileToQiniuAjax(res,0).then(res=>{
			 	resolve(res)
			 }).catch(res=>{
			 	resolve(res)
			 });
		})
	},
	async uploadFileToQiniuAjax(list,key){
		var that = this;
		var info = list[key];
		if(info)
		{
			var qiniuOptions = await that.initQiniu(info.tempFilePath)
		}
		/* console.log(qiniuOptions)
		return ; */
		apiObj.loadingMsg('正在上传文件');
		return new Promise(async (resolve, reject) =>  {
			if(!info || !qiniuOptions || !qiniuOptions.uploadURL )
			{
				var text = !info?'':'获取上传文件配置出错'
				resolve({
					msg:text,
					list:uploadFileListQiniu
				});
				return ;
			}
			uni.request({
			    url: qiniuOptions.uploadURL+'/putb64/-1/key/'+that.encode(qiniuOptions.key), //仅为示例，并非真实接口地址。
			    data: info.tempFilePath.replace(/^.*?base64,/, ''),
				method:'POST',
			    header: {
			        'Content-Type': 'application/octet-stream',
					'Authorization':'UpToken '+qiniuOptions.uptoken,//自定义请求头信息
			    },
			    success: ( res) => {
					if(res.data && res.data.key)
					{
						uploadFileListQiniu.push(res.data.key);
						var text = '';
					}else{
						var text = '上传图片失败：'+res.data.error
					}
					if(text)
					{
						resolve({
							msg:text,
							list:uploadFileListQiniu
						});
						return ;
					}
					var keykey = key+1;
					that.uploadFileToQiniuAjax(list,keykey).then(res=>{
						resolve({
							msg:text,
							list:uploadFileListQiniu
						});
					});
			    },
				fail:(res)=>{
					resolve({
						msg:'网络出现错误',
						list:uploadFileListQiniu
					});
					return;
					//console.log(res)
				}
			});
			
		})
	}

}
